package com.flong.config;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ScheduledFuture;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import com.flong.entity.TaskCron;

/**
 * @Description	 http://blog.csdn.net/m0_38031406/article/details/78051081
 * @ClassName	DynamicTaskSchedule
 * @Date		2018年2月24日 下午3:34:19
 * @Author		liangjl
 * @Copyright (c) All Rights Reserved, 2018.
 */
@Component
@Configuration
@EnableScheduling
public class DynamicTaskSchedule {

	private static final DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
	
	private String cron = "";
	private ScheduledFuture<?> future;
	private int taskSchedulerCorePoolSize = 50;
	//private static boolean isinitialized = false;
	@Autowired private ThreadPoolTaskScheduler threadPoolTaskScheduler;
	
	public String getCron() {
		return cron;
	}

	
    @Bean
    public ThreadPoolTaskScheduler threadPoolTaskScheduler() {
    	threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
    	threadPoolTaskScheduler.setPoolSize(taskSchedulerCorePoolSize);
    	/**需要实例化线程*/
        threadPoolTaskScheduler.initialize();
        //isinitialized = true;
        
        return threadPoolTaskScheduler;
    }
    
    
    
    
    /**
	 * @Description 启动定时任务
	 * @Author		liangjl
	 * @Date		2018年2月24日 下午3:36:05
	 * @param cron 参数
	 * @return void 返回类型 
	 * @throws
     */
	public void startTask(TaskCron task) {
		this.cron = task.getCron();
		//stopCron();
		
		future = threadPoolTaskScheduler.schedule(new Runnable() {
			@Override
			public void run() {
				try {
					System.out.println("动态修改定时任务cron参数，当前时间：" + dateFormat.format(new Date()));
				} catch (Exception e) {
					e.printStackTrace();
					System.out.println("Error:定时生成文件错误");
				}
			}
		}, new Trigger() {
			@Override
			public Date nextExecutionTime(TriggerContext triggerContext) {
				if ("".equals(cron) || cron == null) {
					return null;
				} else {
					CronTrigger trigger = new CronTrigger(cron);// 定时任务触发，可修改定时任务的执行周期
					Date nextExecDate = trigger.nextExecutionTime(triggerContext);
					return nextExecDate;
				}

			}
		});
		
	}
	
	
	/**
	 * @Description 停止定时任务
	 * @Author		liangjl
	 * @Date		2018年2月24日 下午3:35:42 参数
	 * @return void 返回类型 
	 * @throws
	 */
	public void stopTask() {
		if (future != null) {
			future.cancel(true);// 取消任务调度
		}
	}
}